package FenxiaoWithdrawService

import (
	"context"
	"gdshop-admin-go-api/app/request/BaseReq"
	"gdshop-admin-go-api/library/response"
	"gdshop-admin-go-api/library/tools"
	toolsDb "gdshop-admin-go-api/library/tools/db"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
)

func Page(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	ctx := r.GetCtx()
	obj := toolsDb.GetUnSafaTable(ctx, "fenxiao_withdraw").As("fw").
		LeftJoin("member m", "m.id = fw.member_id").
		LeftJoin("fenxiao_user fu", "fw.fenxiao_user_id = fu.id").
		Order("fw.apply_time DESC")
	countObj := toolsDb.GetUnSafaTable(ctx, "fenxiao_withdraw").As("fw").
		LeftJoin("member m", "m.id = fw.member_id").
		LeftJoin("fenxiao_user fu", "fw.fenxiao_user_id = fu.id")
	SelectFields := g.ArrayStr{
		"fw.*",
		"m.realname AS m_realname",
		"fu.name AS fu_name",
	}

	obj.Where("fw.delete_at<1")
	countObj.Where("fw.delete_at<1")

	countObj.Fields("1")
	obj.Fields(SelectFields)

	keyWord := r.GetString("keyWord")
	listType := r.GetInt("list_type")
	whereMap := g.Map{}
	if len(keyWord) > 0 {
		whereMap["m.realname LIKE ? OR fu.name LIKE ?"] = []string{
			"%" + keyWord + "%", "%" + keyWord + "%",
		}
	}
	if listType > 0 {
		whereMap["fw.status"] = listType
	}
	countObj.Where(whereMap)
	obj.Where(whereMap)

	count, err := countObj.Count()
	if err != nil {
		return response.FailByRequestMessage(r, err.Error())
	}

	res, err := obj.Page(req.Page, req.PageSize).All()
	if err != nil {
		return response.FailByRequestMessage(r, err.Error())
	}

	resList := res.List()

	/*for _, item := range resList {

	}*/

	return response.SuccessByRequestMessageData(nil, "获取成功",
		g.Map{
			"list":       resList,
			"pagination": tools.GetPageInfo(count, req.Page, req.PageSize),
		})
}

// 已经获取的佣金
func GetBrokerageByFenxiaoUserId(ctx context.Context, fenxiaoUserId int) float64 {
	sum, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "fenxiao_order_details").Where(
		"status IN (1,90,99) AND fenxiao_user_id = ?", fenxiaoUserId).Sum("(paid * rate / 100000)")
	if err != nil {
		return 0
	}

	return sum
}

// 已提现的佣金
func GetAmountReceivedByFenxiaoUserId(ctx context.Context, fenxiaoUserId int) float64 {
	sum, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "fenxiao_withdraw").Where(
		"status = 99 AND fenxiao_user_id = ?", fenxiaoUserId).Sum("amount_received")
	if err != nil {
		return 0
	}

	return sum
}
